<template>
  <div class="guide-orders-page">
    <div class="page-header mb-6">
      <div class="flex items-center justify-between">
        <h2 class="text-2xl font-bold text-gray-900 dark:text-white">
          导游订单管理
        </h2>
        <div class="flex items-center space-x-2">
          <el-button @click="handleExport">
            <el-icon class="mr-1"><Download /></el-icon>导出数据
          </el-button>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white dark:bg-gray-800 p-6 rounded-lg shadow-sm mb-6">
      <div class="flex flex-wrap gap-4 mb-4">
        <el-input
          v-model="searchForm.keyword"
          placeholder="搜索订单号/导游姓名/用户姓名"
          class="!w-64"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-select
          v-model="searchForm.status"
          placeholder="订单状态"
          clearable
          class="!w-32"
        >
          <el-option label="全部" value="" />
          <el-option label="待付款" value="unpaid" />
          <el-option label="待服务" value="paid" />
          <el-option label="服务中" value="processing" />
          <el-option label="已完成" value="completed" />
          <el-option label="已取消" value="cancelled" />
          <el-option label="退款中" value="refunding" />
          <el-option label="已退款" value="refunded" />
        </el-select>

        <el-date-picker
          v-model="searchForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          class="!w-80"
        />

        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
    </div>

    <!-- 订单列表 -->
    <div class="bg-white dark:bg-gray-800 p-6 rounded-lg shadow-sm">
      <el-tabs v-model="activeTab" @tab-click="handleTabChange">
        <el-tab-pane label="全部订单" name="all">
          <template #label>
            全部订单
            <el-badge
              v-if="tabCounts.all"
              :value="tabCounts.all"
              class="ml-2"
            />
          </template>
        </el-tab-pane>
        <el-tab-pane label="待付款" name="unpaid">
          <template #label>
            待付款
            <el-badge
              v-if="tabCounts.unpaid"
              :value="tabCounts.unpaid"
              class="ml-2"
              type="warning"
            />
          </template>
        </el-tab-pane>
        <el-tab-pane label="待服务" name="paid">
          <template #label>
            待服务
            <el-badge
              v-if="tabCounts.paid"
              :value="tabCounts.paid"
              class="ml-2"
              type="primary"
            />
          </template>
        </el-tab-pane>
        <el-tab-pane label="已完成" name="completed">
          <template #label>
            已完成
            <el-badge
              v-if="tabCounts.completed"
              :value="tabCounts.completed"
              class="ml-2"
              type="success"
            />
          </template>
        </el-tab-pane>
        <el-tab-pane label="已取消/退款" name="cancelled">
          <template #label>
            已取消/退款
            <el-badge
              v-if="tabCounts.cancelled"
              :value="tabCounts.cancelled"
              class="ml-2"
              type="info"
            />
          </template>
        </el-tab-pane>
      </el-tabs>

      <el-table
        v-loading="loading"
        :data="ordersList"
        border
        style="width: 100%"
        row-key="orderNo"
      >
        <el-table-column label="订单信息" min-width="200">
          <template #default="{ row }">
            <div class="space-y-1">
              <div class="text-sm font-medium">订单号：{{ row.orderNo }}</div>
              <div class="text-sm text-gray-500">
                下单时间：{{ formatDateTime(row.createTime) }}
              </div>
              <div class="flex items-center mt-1">
                <el-tag :type="getStatusType(row.status)">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="导游信息" min-width="200">
          <template #default="{ row }">
            <div class="flex items-center space-x-3">
              <el-avatar :size="40" :src="row.guide.avatar" />
              <div>
                <div class="text-sm font-medium">{{ row.guide.name }}</div>
                <div class="text-xs text-gray-500">ID: {{ row.guide.id }}</div>
                <div class="text-xs text-gray-500">
                  电话: {{ row.guide.phone }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="用户信息" min-width="200">
          <template #default="{ row }">
            <div class="flex items-center space-x-3">
              <el-avatar :size="40" :src="row.user.avatar" />
              <div>
                <div class="text-sm font-medium">{{ row.user.name }}</div>
                <div class="text-xs text-gray-500">ID: {{ row.user.id }}</div>
                <div class="text-xs text-gray-500">
                  电话: {{ row.user.phone }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="服务信息" min-width="250">
          <template #default="{ row }">
            <div class="space-y-1">
              <div class="text-sm">
                <span class="text-gray-500">路线名称：</span>
                <span>{{ row.booking.routeName || "自定义行程" }}</span>
              </div>
              <div class="text-sm">
                <span class="text-gray-500">服务日期：</span>
                <span>{{ row.booking.guideDate }}</span>
              </div>
              <div class="text-sm">
                <span class="text-gray-500">开始时间：</span>
                <span>{{ row.booking.guideTime }}</span>
              </div>
              <div class="text-sm">
                <span class="text-gray-500">游客人数：</span>
                <span>{{ row.booking.people }}人</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="金额信息" min-width="150">
          <template #default="{ row }">
            <div class="space-y-1">
              <div class="text-sm">
                <span class="text-gray-500">订单金额：</span>
                <span class="font-medium text-primary-600"
                  >¥{{ row.payableAmount.toFixed(2) }}</span
                >
              </div>
              <div
                class="text-sm"
                v-if="row.status === 'refunded' || row.status === 'refunding'"
              >
                <span class="text-gray-500">退款金额：</span>
                <span class="font-medium text-red-500"
                  >¥{{ row.refundAmount?.toFixed(2) || 0 }}</span
                >
              </div>
              <div class="text-sm">
                <span class="text-gray-500">支付方式：</span>
                <span>{{ getPaymentMethod(row.paymentMethod) }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right" width="120">
          <template #default="{ row }">
            <div class="flex flex-col space-y-1 items-end">
              <el-button
                size="small"
                class="op-btn"
                @click="handleViewDetail(row)"
                >查看详情</el-button
              >

              <el-button
                v-if="row.status === 'refunding'"
                size="small"
                type="warning"
                class="op-btn"
                @click="handleRefund(row)"
                >处理退款</el-button
              >

              <el-button
                v-if="row.status === 'paid' || row.status === 'processing'"
                size="small"
                type="danger"
                class="op-btn"
                @click="handleCancel(row)"
                >取消订单</el-button
              >
            </div>
          </template>
        </el-table-column>
        
        <template #empty>
          <div class="empty-state">
            <el-empty 
              description="暂无订单数据" 
              :image-size="200"
            >
              <div class="empty-text">当前没有任何导游订单</div>
              <div class="empty-subtext">用户预订导游服务后会在此处显示</div>
            </el-empty>
          </div>
        </template>
      </el-table>

      <!-- 分页 -->
      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 退款处理对话框 -->
    <el-dialog
      v-model="refundDialogVisible"
      title="退款处理"
      width="500px"
      destroy-on-close
    >
      <div v-if="currentOrder" class="space-y-4">
        <div class="bg-gray-50 dark:bg-gray-700 p-4 rounded-lg">
          <div class="text-sm mb-2">
            <span class="text-gray-500">订单号：</span>
            <span class="font-medium">{{ currentOrder.orderNo }}</span>
          </div>
          <div class="text-sm mb-2">
            <span class="text-gray-500">退款金额：</span>
            <span class="font-medium text-red-500"
              >¥{{
                currentOrder.refundAmount?.toFixed(2) ||
                currentOrder.payableAmount.toFixed(2)
              }}</span
            >
          </div>
          <div class="text-sm">
            <span class="text-gray-500">退款原因：</span>
            <span>{{ currentOrder.refundReason || "用户申请退款" }}</span>
          </div>
        </div>

        <el-form :model="refundForm" label-width="100px">
          <el-form-item label="退款状态">
            <el-radio-group v-model="refundForm.status">
              <el-radio label="approved">同意退款</el-radio>
              <el-radio label="rejected">拒绝退款</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="退款金额"
            v-if="refundForm.status === 'approved'"
          >
            <el-input-number
              v-model="refundForm.amount"
              :min="0"
              :max="currentOrder?.payableAmount || 0"
              :precision="2"
              :step="10"
              class="!w-full"
            />
          </el-form-item>
          <el-form-item label="处理说明">
            <el-input
              v-model="refundForm.comment"
              type="textarea"
              rows="3"
              placeholder="请输入处理说明"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="flex justify-end">
          <el-button @click="refundDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmRefund">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 取消订单对话框 -->
    <el-dialog
      v-model="cancelDialogVisible"
      title="取消订单"
      width="500px"
      destroy-on-close
    >
      <div v-if="currentOrder" class="space-y-4">
        <div class="bg-gray-50 dark:bg-gray-700 p-4 rounded-lg">
          <div class="text-sm mb-2">
            <span class="text-gray-500">订单号：</span>
            <span class="font-medium">{{ currentOrder.orderNo }}</span>
          </div>
          <div class="text-sm mb-2">
            <span class="text-gray-500">订单金额：</span>
            <span class="font-medium text-primary-600"
              >¥{{ currentOrder.payableAmount.toFixed(2) }}</span
            >
          </div>
          <div class="text-sm">
            <span class="text-gray-500">服务日期：</span>
            <span>{{ currentOrder.booking?.guideDate }}</span>
          </div>
        </div>

        <el-form :model="cancelForm" label-width="100px">
          <el-form-item label="取消原因" prop="reason">
            <el-select
              v-model="cancelForm.reason"
              placeholder="请选择取消原因"
              class="w-full"
            >
              <el-option label="导游临时有事" value="guide_unavailable" />
              <el-option label="用户要求取消" value="user_request" />
              <el-option label="天气原因" value="weather" />
              <el-option label="安全问题" value="safety" />
              <el-option label="其他原因" value="other" />
            </el-select>
          </el-form-item>
          <el-form-item label="退款金额">
            <el-input-number
              v-model="cancelForm.refundAmount"
              :min="0"
              :max="currentOrder?.payableAmount || 0"
              :precision="2"
              :step="10"
              class="!w-full"
            />
          </el-form-item>
          <el-form-item label="详细说明">
            <el-input
              v-model="cancelForm.comment"
              type="textarea"
              rows="3"
              placeholder="请输入详细说明"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="flex justify-end">
          <el-button @click="cancelDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCancel">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 订单详情模态框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="800px"
      destroy-on-close
      append-to-body
      :before-close="handleCloseDetailDialog"
      @open="disableBodyScroll"
      @close="enableBodyScroll"
      class="order-detail-dialog"
    >
      <div v-if="currentOrder" class="order-detail dialog-scrollable">
        <div
          class="flex justify-between items-center pb-4 border-b dark:border-gray-700"
        >
          <div>
            <h3 class="text-xl font-bold">
              订单号：{{ currentOrder.orderNo }}
            </h3>
            <div class="text-sm text-gray-500 mt-1">
              下单时间：{{ formatDateTime(currentOrder.createTime) }}
            </div>
          </div>
          <el-tag :type="getStatusType(currentOrder.status)" size="large">
            {{ getStatusText(currentOrder.status) }}
          </el-tag>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mt-6">
          <!-- 导游信息 -->
          <div class="card">
            <h4 class="card-title">导游信息</h4>
            <div class="flex items-center space-x-4 mb-4">
              <el-avatar :size="60" :src="currentOrder.guide.avatar" />
              <div>
                <div class="text-lg font-medium">
                  {{ currentOrder.guide.name }}
                </div>
                <div class="text-sm text-gray-500">
                  ID: {{ currentOrder.guide.id }}
                </div>
                <div class="text-sm text-gray-500">
                  联系电话: {{ currentOrder.guide.phone }}
                </div>
              </div>
            </div>
          </div>

          <!-- 用户信息 -->
          <div class="card">
            <h4 class="card-title">用户信息</h4>
            <div class="flex items-center space-x-4 mb-4">
              <el-avatar :size="60" :src="currentOrder.user.avatar" />
              <div>
                <div class="text-lg font-medium">
                  {{ currentOrder.user.name }}
                </div>
                <div class="text-sm text-gray-500">
                  ID: {{ currentOrder.user.id }}
                </div>
                <div class="text-sm text-gray-500">
                  联系电话: {{ currentOrder.user.phone }}
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 服务信息 -->
        <div class="card mt-6">
          <h4 class="card-title">服务信息</h4>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div class="text-sm">
              <span class="text-gray-500">路线名称：</span>
              <span>{{ currentOrder.booking.routeName || "自定义行程" }}</span>
            </div>
            <div class="text-sm">
              <span class="text-gray-500">服务地点：</span>
              <span>{{ currentOrder.booking.location || "用户指定地点" }}</span>
            </div>
            <div class="text-sm">
              <span class="text-gray-500">服务日期：</span>
              <span>{{ currentOrder.booking.guideDate }}</span>
            </div>
            <div class="text-sm">
              <span class="text-gray-500">开始时间：</span>
              <span>{{ currentOrder.booking.guideTime }}</span>
            </div>
            <div class="text-sm">
              <span class="text-gray-500">服务时长：</span>
              <span>{{ currentOrder.booking.duration || "一天" }}</span>
            </div>
            <div class="text-sm">
              <span class="text-gray-500">游客人数：</span>
              <span>{{ currentOrder.booking.people }}人</span>
            </div>
          </div>

          <div class="mt-4" v-if="currentOrder.booking.specialRequests">
            <div class="text-sm text-gray-500">特殊要求：</div>
            <div class="mt-1 p-3 bg-gray-50 dark:bg-gray-700 rounded">
              {{ currentOrder.booking.specialRequests }}
            </div>
          </div>
        </div>

        <!-- 费用信息 -->
        <div class="card mt-6">
          <h4 class="card-title">费用信息</h4>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div class="text-sm">
              <span class="text-gray-500">服务费用：</span>
              <span class="font-medium"
                >¥{{ currentOrder.guideAmount?.toFixed(2) || "0.00" }}</span
              >
            </div>
            <div class="text-sm">
              <span class="text-gray-500">平台服务费：</span>
              <span class="font-medium"
                >¥{{ currentOrder.platformFee?.toFixed(2) || "0.00" }}</span
              >
            </div>
            <div class="text-sm font-medium">
              <span class="text-gray-500">订单总额：</span>
              <span class="text-primary-600"
                >¥{{ currentOrder.payableAmount.toFixed(2) }}</span
              >
            </div>
            <div class="text-sm">
              <span class="text-gray-500">支付方式：</span>
              <span>{{ getPaymentMethod(currentOrder.paymentMethod) }}</span>
            </div>
            <div class="text-sm" v-if="currentOrder.payTime">
              <span class="text-gray-500">支付时间：</span>
              <span>{{ formatDateTime(currentOrder.payTime) }}</span>
            </div>
          </div>

          <div
            class="mt-4"
            v-if="
              currentOrder.status === 'refunded' ||
              currentOrder.status === 'refunding'
            "
          >
            <el-divider content-position="left">退款信息</el-divider>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div class="text-sm">
                <span class="text-gray-500">申请时间：</span>
                <span>{{ formatDateTime(currentOrder.refundApplyTime) }}</span>
              </div>
              <div class="text-sm">
                <span class="text-gray-500">退款原因：</span>
                <span>{{ currentOrder.refundReason || "用户申请退款" }}</span>
              </div>
              <div class="text-sm font-medium">
                <span class="text-gray-500">退款金额：</span>
                <span class="text-red-500"
                  >¥{{ currentOrder.refundAmount?.toFixed(2) || "0.00" }}</span
                >
              </div>
              <div class="text-sm" v-if="currentOrder.refundTime">
                <span class="text-gray-500">退款时间：</span>
                <span>{{ formatDateTime(currentOrder.refundTime) }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="flex justify-center mt-6 space-x-4">
          <el-button
            v-if="currentOrder.status === 'refunding'"
            type="warning"
            @click="handleRefund(currentOrder)"
            >处理退款</el-button
          >

          <el-button
            v-if="
              currentOrder.status === 'paid' ||
              currentOrder.status === 'processing'
            "
            type="danger"
            @click="handleCancel(currentOrder)"
            >取消订单</el-button
          >
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Download } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import * as XLSX from 'xlsx';
import axios from '@/api/axios';

const router = useRouter();
const route = useRoute();
const loading = ref(false);
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);
const activeTab = ref("all");

// 从路由获取导游ID（如果有）
const guideId = computed(() => route.query.guideId);

// 搜索表单
const searchForm = reactive({
  keyword: "",
  status: "",
  dateRange: [],
});

// 各标签页数量统计
const tabCounts = reactive({
  all: 0,
  unpaid: 0,
  paid: 0,
  completed: 0,
  cancelled: 0
});

// 模拟订单数据（备用）
const mockOrdersList = [
  {
    orderNo: "GD202401001",
    createTime: "2024-01-05 09:30:00",
    status: "completed",
    guide: {
      id: 1,
      name: "李明",
      avatar: "/images/guides/guide1.jpg",
      phone: "13800138000"
    },
    user: {
      id: 101,
      name: "张先生",
      avatar: "/images/users/user1.jpg",
      phone: "13900139000"
    },
    booking: {
      routeName: "桂林市区一日游",
      guideDate: "2024-01-10",
      guideTime: "09:00",
      people: 3
    },
    payableAmount: 380,
    paymentMethod: "wechat",
    completionTime: "2024-01-10 18:30:00",
    review: {
      rating: 5,
      comment: "导游专业知识丰富，讲解生动有趣，服务态度很好。"
    }
  },
  {
    orderNo: "GD202401002",
    createTime: "2024-01-08 14:20:00",
    status: "paid",
    guide: {
      id: 2,
      name: "张华",
      avatar: "/images/guides/guide2.jpg",
      phone: "13700137000"
    },
    user: {
      id: 102,
      name: "王女士",
      avatar: "/images/users/user2.jpg",
      phone: "13600136000"
    },
    booking: {
      routeName: "阳朔漓江风光游",
      guideDate: "2024-01-15",
      guideTime: "08:30",
      people: 2
    },
    payableAmount: 450,
    paymentMethod: "alipay"
  },
  {
    orderNo: "GD202401003",
    createTime: "2024-01-10 16:45:00",
    status: "unpaid",
    guide: {
      id: 3,
      name: "王丽",
      avatar: "/images/guides/guide3.jpg",
      phone: "13500135000"
    },
    user: {
      id: 103,
      name: "李先生",
      avatar: "/images/users/user3.jpg",
      phone: "13400134000"
    },
    booking: {
      routeName: "贵港骑楼老街探访",
      guideDate: "2024-01-20",
      guideTime: "10:00",
      people: 4
    },
    payableAmount: 320,
    paymentMethod: null
  },
  {
    orderNo: "GD202401004",
    createTime: "2024-01-12 10:15:00",
    status: "refunding",
    guide: {
      id: 1,
      name: "李明",
      avatar: "/images/guides/guide1.jpg", 
      phone: "13800138000"
    },
    user: {
      id: 104,
      name: "赵女士",
      avatar: "/images/users/user4.jpg",
      phone: "13300133000"
    },
    booking: {
      routeName: "自定义行程",
      guideDate: "2024-01-18",
      guideTime: "09:30",
      people: 2
    },
    payableAmount: 380,
    paymentMethod: "wechat",
    refundAmount: 380
  },
  {
    orderNo: "GD202401005",
    createTime: "2024-01-15 08:30:00",
    status: "cancelled",
    guide: {
      id: 2,
      name: "张华",
      avatar: "/images/guides/guide2.jpg",
      phone: "13700137000"
    },
    user: {
      id: 105,
      name: "刘先生",
      avatar: "/images/users/user5.jpg",
      phone: "13200132000"
    },
    booking: {
      routeName: "平南古镇文化游",
      guideDate: "2024-01-25",
      guideTime: "10:00",
      people: 5
    },
    payableAmount: 450,
    paymentMethod: "alipay",
    cancelTime: "2024-01-16 09:20:00",
    cancelReason: "行程计划有变"
  }
];

const ordersList = ref([]);

// 格式化日期时间
const formatDateTime = (date) => {
  return date ? dayjs(date).format("YYYY-MM-DD HH:mm:ss") : '';
};

// 获取状态显示文本
const getStatusText = (status) => {
  const statusMap = {
    unpaid: "待付款",
    paid: "待服务",
    processing: "服务中",
    completed: "已完成",
    cancelled: "已取消",
    refunding: "退款中",
    refunded: "已退款"
  };
  return statusMap[status] || status;
};

// 获取状态对应的类型
const getStatusType = (status) => {
  const typeMap = {
    unpaid: "warning",
    paid: "primary",
    processing: "success",
    completed: "success",
    cancelled: "info",
    refunding: "danger",
    refunded: "info"
  };
  return typeMap[status] || "info";
};

// 获取支付方式文本
const getPaymentMethod = (method) => {
  const methodMap = {
    wechat: "微信支付",
    alipay: "支付宝",
    creditcard: "信用卡",
    bankcard: "银行卡"
  };
  return method ? methodMap[method] || method : "未支付";
};

// 获取订单列表
const getOrdersList = async () => {
  loading.value = true;
  try {
    const params = {
      page: page.value,
      pageSize: pageSize.value,
      ...searchForm
    };
    
    // 处理日期范围
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0];
      params.endDate = searchForm.dateRange[1];
      delete params.dateRange;
    }
    
    // 处理标签页筛选
    if (activeTab.value !== "all") {
      params.status = activeTab.value;
    }
    
    // 如果有导游ID，添加到参数
    if (guideId.value) {
      params.guideId = guideId.value;
    }
    
    const response = await axios.get('/admin/guides/orders', { params });
    
    if (response && response.code === 200 && response.data) {
      ordersList.value = response.data.list || [];
      total.value = response.data.total || 0;
      
      // 更新标签页数量
      if (response.data.counts) {
        Object.keys(tabCounts).forEach(key => {
          tabCounts[key] = response.data.counts[key] || 0;
        });
      }
    } else {
      // 使用模拟数据
      let filteredOrders = [...mockOrdersList];
      
      // 按标签筛选
      if (activeTab.value !== "all") {
        filteredOrders = filteredOrders.filter(order => {
          if (activeTab.value === "cancelled") {
            return order.status === "cancelled" || order.status === "refunded";
          }
          return order.status === activeTab.value;
        });
      }
      
      // 按导游ID筛选
      if (guideId.value) {
        filteredOrders = filteredOrders.filter(order => 
          order.guide.id.toString() === guideId.value.toString()
        );
      }
      
      // 按关键词筛选
      if (searchForm.keyword) {
        const keyword = searchForm.keyword.toLowerCase();
        filteredOrders = filteredOrders.filter(order => 
          order.orderNo.toLowerCase().includes(keyword) || 
          order.guide.name.toLowerCase().includes(keyword) || 
          order.user.name.toLowerCase().includes(keyword)
        );
      }
      
      ordersList.value = filteredOrders;
      total.value = filteredOrders.length;
      
      // 统计各状态数量
      const counts = filteredOrders.reduce((acc, order) => {
        acc.all = (acc.all || 0) + 1;
        
        if (order.status === "cancelled" || order.status === "refunded") {
          acc.cancelled = (acc.cancelled || 0) + 1;
        } else {
          acc[order.status] = (acc[order.status] || 0) + 1;
        }
        
        return acc;
      }, {});
      
      // 更新标签页数量
      Object.keys(tabCounts).forEach(key => {
        tabCounts[key] = counts[key] || 0;
      });
    }
  } catch (error) {
    console.error("获取订单列表失败:", error);
    ElMessage.error("获取订单列表失败，使用测试数据");
    // 使用模拟数据
    let filteredOrders = [...mockOrdersList];
    
    // 按标签筛选
    if (activeTab.value !== "all") {
      filteredOrders = filteredOrders.filter(order => {
        if (activeTab.value === "cancelled") {
          return order.status === "cancelled" || order.status === "refunded";
        }
        return order.status === activeTab.value;
      });
    }
    
    // 按导游ID筛选
    if (guideId.value) {
      filteredOrders = filteredOrders.filter(order => 
        order.guide.id.toString() === guideId.value.toString()
      );
    }
    
    ordersList.value = filteredOrders;
    total.value = filteredOrders.length;
    
    // 统计各状态数量
    const counts = mockOrdersList.reduce((acc, order) => {
      acc.all = (acc.all || 0) + 1;
      
      if (order.status === "cancelled" || order.status === "refunded") {
        acc.cancelled = (acc.cancelled || 0) + 1;
      } else {
        acc[order.status] = (acc[order.status] || 0) + 1;
      }
      
      return acc;
    }, {});
    
    // 更新标签页数量
    Object.keys(tabCounts).forEach(key => {
      tabCounts[key] = counts[key] || 0;
    });
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  page.value = 1;
  getOrdersList();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  searchForm.dateRange = [];
  page.value = 1;
  getOrdersList();
};

// 标签页切换
const handleTabChange = () => {
  page.value = 1;
  getOrdersList();
};

// 查看订单详情
const handleViewDetail = (row) => {
  currentOrder.value = row;
  detailDialogVisible.value = true;
};

// 处理退款
const handleRefund = async (row) => {
  router.push({
    path: '/admin/guides/refunds',
    query: { refundId: row.refundId || row.orderNo }
  });
};

// 取消订单
const handleCancel = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消订单 ${row.orderNo} 吗？`,
      "取消订单确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    try {
      await axios.put(`/admin/guides/orders/${row.orderNo}/cancel`, {
        cancelReason: "管理员取消",
        cancelTime: new Date(),
      });
      
      ElMessage.success("订单已取消");
      getOrdersList();
    } catch (error) {
      console.error("取消订单失败:", error);
      ElMessage.error("取消订单失败");
    }
  } catch (error) {
    if (error === "cancel") return;
  }
};

// 导出数据
const handleExport = () => {
  // 准备导出数据
  const exportData = ordersList.value.map(order => ({
    订单号: order.orderNo,
    下单时间: formatDateTime(order.createTime),
    订单状态: getStatusText(order.status),
    导游ID: order.guide.id,
    导游姓名: order.guide.name,
    导游电话: order.guide.phone,
    用户ID: order.user.id,
    用户姓名: order.user.name,
    用户电话: order.user.phone,
    路线名称: order.booking.routeName || "自定义行程",
    服务日期: order.booking.guideDate,
    开始时间: order.booking.guideTime,
    游客人数: order.booking.people,
    订单金额: `¥${order.payableAmount.toFixed(2)}`,
    支付方式: getPaymentMethod(order.paymentMethod),
    退款金额: order.refundAmount ? `¥${order.refundAmount.toFixed(2)}` : '-',
    完成时间: order.completionTime ? formatDateTime(order.completionTime) : '-',
    取消时间: order.cancelTime ? formatDateTime(order.cancelTime) : '-',
    取消原因: order.cancelReason || '-',
    评分: order.review?.rating || '-',
    评价内容: order.review?.comment || '-'
  }));

  // 创建工作簿
  const workbook = XLSX.utils.book_new();
  const worksheet = XLSX.utils.json_to_sheet(exportData);
  
  // 添加工作表到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, '导游订单管理');
  
  // 导出Excel文件
  XLSX.writeFile(workbook, `导游订单管理_${dayjs().format('YYYYMMDD_HHmmss')}.xlsx`);
  
  ElMessage.success("导游订单数据导出成功");
};

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val;
  getOrdersList();
};

const handleCurrentChange = (val) => {
  page.value = val;
  getOrdersList();
};

// 详情对话框相关
const detailDialogVisible = ref(false);
const currentOrder = ref(null);

// 禁用/启用页面滚动
const disableBodyScroll = () => {
  document.body.style.overflow = "hidden";
};

const enableBodyScroll = () => {
  document.body.style.overflow = "";
};

// 关闭详情模态框
const handleCloseDetailDialog = () => {
  detailDialogVisible.value = false;
};

// 返回
const goBack = () => {
  router.back();
};

// 页面加载时获取数据
onMounted(() => {
  getOrdersList();
});
</script>

<style lang="scss" scoped>
.guide-orders-page {
  padding: 20px;

  :deep(.el-tabs__header) {
    margin-bottom: 20px;
  }

  :deep(.el-table) {
    --el-table-border-color: var(--el-border-color-lighter);
    --el-table-header-bg-color: var(--el-fill-color-light);

    .el-table__header th {
      font-weight: 600;
      color: var(--el-text-color-primary);
    }

    .dark & {
      --el-table-border-color: var(--el-border-color-darker);
      --el-table-header-bg-color: var(--el-bg-color-overlay);

      .el-table__header th {
        color: var(--el-text-color-primary);
      }
    }
  }

  .card {
    background-color: var(--el-bg-color-overlay);
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    border: 1px solid var(--el-border-color-lighter);

    .dark & {
      border-color: var(--el-border-color-darker);
    }
  }

  .card-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 16px;
    padding-bottom: 8px;
    border-bottom: 1px solid var(--el-border-color-lighter);
    color: var(--el-text-color-primary);

    .dark & {
      border-color: var(--el-border-color-darker);
    }
  }
}

// 添加模态框样式
:deep(.order-detail-dialog) {
  .el-dialog__header {
    position: sticky;
    top: 0;
    z-index: 10;
    background-color: var(--el-bg-color);
    margin-right: 0;
    padding: 20px 20px 10px;
    border-bottom: 1px solid var(--el-border-color-lighter);
  }

  .el-dialog__body {
    padding: 0;
    max-height: calc(80vh - 120px);
    overflow-y: auto;
  }

  .dialog-scrollable {
    padding: 20px;
  }

  .el-dialog__footer {
    position: sticky;
    bottom: 0;
    z-index: 10;
    background-color: var(--el-bg-color);
    padding: 10px 20px 20px;
    border-top: 1px solid var(--el-border-color-lighter);
  }
}

// 添加样式
.op-btn {
  width: 90px !important;
  margin-left: 0 !important;
  margin-right: 0 !important;
}

.empty-state {
  padding: 30px 0;
  max-height: 400px;
}

.empty-text {
  font-size: 16px;
  color: var(--el-text-color-secondary);
  margin-top: 10px;
}

.empty-subtext {
  font-size: 14px;
  color: var(--el-text-color-placeholder);
  margin-top: 5px;
}

.mt-4 {
  margin-top: 16px;
}
</style>
